package com.jd.util;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.region.Region;

import java.io.File;

/**
 * @Description: 上传工具类(高依赖版)
 * @Date: 2019/5/10
 */
public class CosBootUtil {

    private static final String endPoint = "cos.ap-nanjing.myqcloud.com";

    /**
     * 上传文件至腾讯云 COS
     * 文件上传成功,返回文件完整访问路径
     * 文件上传失败,返回 null
     *
     * @param file    待上传文件
     * @param fileDir 文件保存目录
     * @return oss 中的相对文件路径
     */
    public static String upload(File file, String fileDir) {
        // 1 初始化用户身份信息(secretId, secretKey)============
        COSCredentials cred = new BasicCOSCredentials("AKIDjHgryJuIVXLzOlr64rTonXAbzBRLIlCT", "ymAVcfTyEORwVpoaJmzINC8cwymT0Rhi");
        // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region("ap-nanjing"));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // bucket名需包含appid
        String bucketName = "bfdj-1304596505";//桶
        StringBuilder fileUrl = new StringBuilder();
        // 获取文件名
        String orgName = file.getName();
        orgName = CommonUtils.getFileName(orgName);
        String fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
        if (!fileDir.endsWith("/")) {
            fileDir = fileDir.concat("/");
        }
        fileUrl = fileUrl.append(fileDir + fileName);

        //拼接返回值
        String FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;

        try {
            String key = fileUrl.toString();
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
            /*if(useTrafficLimit) {
                // 限流使用的单位是bit/s, 这里测试1MB/s的上传带宽限制
                putObjectRequest.setTrafficLimit(8*1024*1024);
            }*/
            // 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
            putObjectRequest.setStorageClass(StorageClass.Standard);

            PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
            // putobjectResult会返回文件的etag
            /*String etag = putObjectResult.getETag();
            String crc64 = putObjectResult.getCrc64Ecma();*/
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 关闭客户端
        cosclient.shutdown();

        return FILE_URL;
    }

    /**
     * 删除本地临时文件
     * @param file
     */
    public static void delteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }
}